package com.boot.controller;

import com.boot.entity.Major;
import com.boot.entity.School;
import com.boot.repository.MajorRepository;
import com.boot.repository.SchoolRepository;
import com.boot.vo.BaseMessage;
import com.boot.vo.MessageHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin(origins = "*")

@RequestMapping("/major")
public class MajorController {

    @Autowired
    private MajorRepository majorRepository;

    @Autowired
    private SchoolRepository schoolRepository;
    @GetMapping("majorList")
    public BaseMessage<?> majorList(String keyword) {
        List<Major> all = majorRepository.findAllByMajorNameLike(keyword);
        return MessageHandler.createSuccessVo(all, "success");
    }
/*    @GetMapping
    public BaseMessage<?> majorList(String keyword) {
        List<Major> all= majorRepository.findAllByMajorNameLike(keyword);

        Set<Integer> schoolIds = all.stream().map(Major::getSchoolId).collect(Collectors.toSet());
        List<School> schools = schoolRepository.findAllById(schoolIds);
        Map<Integer, String> id2Name = schools.stream().collect(Collectors.toMap(School::getSchoolId, School::getSchoolName));
        all.forEach(x -> x.setSchoolName(id2Name.get(x.getSchoolId())));
        return MessageHandler.createSuccessVo(all, "success");
    }*/

    @DeleteMapping("delMajor/{id}")
    public BaseMessage<String> delMajor(@PathVariable Integer id) {
        Boolean b=majorRepository.existsByMajorId(id);
        if(b==false)
            return MessageHandler.createFailedVo("该专业不存在");
        Major major = majorRepository.findByMajorId(id);
        if(major.getStuNum()>0 || major.getTeaNum()>0){
            return MessageHandler.createFailedVo("该专业下注册有老师/学生,不可直接删除");
        }
        majorRepository.delete(major);

        return MessageHandler.createSuccessVo("专业删除成功");
    }

    //添加专业
    @RequestMapping("addMajor")
    public BaseMessage<?> addMajor(Major major){
        Boolean b = majorRepository.existsByMajorId(major.getMajorId());
        if(b ==true)
            return MessageHandler.createFailedVo("该专业已存在，不可重复添加！");
        if(StringUtils.isBlank(major.getMajorName()) || StringUtils.isBlank(major.getMajorId().toString()))
            return MessageHandler.createFailedVo("专业id或名称不为空");
        major.setTeaNum(0);major.setStuNum(0);
        majorRepository.save(major);
        return MessageHandler.createFailedVo("专业添加成功");

    }

    // 编辑专业
    @RequestMapping("editMajor")
    @ResponseBody
    public BaseMessage<?> editMajor (Major major){
        Boolean b =majorRepository.existsByMajorId(major.getMajorId());
        if(b==false)
            return MessageHandler.createFailedVo("专业id不存在");
        else {
            majorRepository.save(major);
            return MessageHandler.createSuccessVo("专业编辑成功");
        }
    }
}
